package com.ktjiaoyu.crm.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktjiaoyu.crm.mapper.UserMapper;
import com.ktjiaoyu.crm.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;

@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public User login(String usrName, String usrPassword) {
        //条件构造器
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("usr_name",usrName);
        queryWrapper.eq("usr_password",usrPassword);
        return userMapper.selectOne(queryWrapper);
    }

    @Cacheable(value = "userList",key = "#page.current+'-'+#page.size+'-'+#userName+'-'+#roleId")
    @Override
    public Page<User> selectUserPages(Page<User> page, String userName,Long roleId) {
        //条件构造器
        QueryWrapper queryWrapper = new QueryWrapper();
        if(userName != null && !"".equals(userName)){
            queryWrapper.like("usr_name",userName);
        }
        if(roleId!=null && roleId!=0){
            queryWrapper.eq("usr_role_id",roleId);
        }

        return page.setRecords(userMapper.selectUserPages(page,queryWrapper));
    }


    @CacheEvict(value = "{usetList}")
    @Override
    public boolean addUsers(User user) {

        return userMapper.addUsers(user);
    }


    @Cacheable(value = "user",key = "#userId")
    @Override
    public User getUserById(Long userId) {

        return userMapper.selectById(userId);
    }

    @CachePut(value = "user",key = "#user.usrId")
    @Override
    public User updateUser(User user) {
        userMapper.updateById(user);
        return user;
    }

    @CacheEvict(value = "user")
    @Override
    public boolean removeById(Serializable id) {

        return super.removeById(id);
    }

    /**
     * 根据用户名查询用户信息
     * @param name
     * @return
     */
    @Override
    public User getUesrByName(String name) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("usr_name",name);
        return userMapper.getUesrByName(queryWrapper);
    }
}
